/**
 * Created by tanbingqin on 2020/7/21.
 */
import React, { Component, PropTypes } from "react";
import { messages, deepFullCopy, queryCurrencyPrecision, eventTrack } from 'share/common'
import { connect } from 'react-redux';
import moment from 'moment'
import config from 'config'
import travelService from 'containers/request/travel-request/travel.service'
import requestService from 'containers/request/request.service'
import errorMessage from 'share/errorMessage';
import 'styles/request/new-card-request.scss'
import { Button, Row, Col, Icon, Alert, message, Popconfirm, Spin, InputNumber } from 'antd'
import Condition from 'components/condition';
const If = Condition.If;
import travelUtil from 'containers/request/travel-request/travelUtil'
import requestUtil from 'containers/request/slide/request-util'

class RequestSubsidyDetail extends Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      subsidyInfo: {},
      isOpen: false, //是否展开明细
    };
  }

  componentDidMount() {
    this.setState({subsidyInfo: JSON.parse(JSON.stringify(this.props.subsidyInfo))});
  }

  componentWillReceiveProps(nextProps) {}

  toggleDrop = () => {
    const { isOpen } = this.state;
    if (isOpen) {
      eventTrack({
        category: '计算补贴',
        action: '明细收起'
      });
    } else {
      eventTrack({
        category: '计算补贴',
        action: '明细展开'
      });
    }
    this.setState({isOpen: !isOpen});
  };

  handleEdit = (detailIndex) => {
    eventTrack({
      category: '计算补贴',
      action: '编辑单个差补明细'
    });
    let subsidyInfo = JSON.parse(JSON.stringify(this.props.subsidyInfo));
    subsidyInfo.travelSubsidiesRequestItemDetailDTOs[detailIndex].isEdit = true;
    this.setState({subsidyInfo});
  };

  handleCancel = () => {
    eventTrack({
      category: '计算补贴',
      action: '差补明细行-取消'
    });
    this.setState({subsidyInfo: JSON.parse(JSON.stringify(this.props.subsidyInfo))});
  };

  //是否显示编辑按钮
  isShowEdit = () => {
    const { newProfile } = this.props;
    const { prohibitExchangeRateTol } = this.props.params;
    let amountModify = newProfile['subsidyControlOpt']['amountModify'];
    let isShowEdit = false;
    if (prohibitExchangeRateTol !== 0 || amountModify === 1002 || amountModify === 1003) {
      isShowEdit = true;
    }
    return isShowEdit;
  };

  currencyRateChange = (value, detailIndex) => {
    let { subsidyInfo } = this.state;
    let detail = subsidyInfo.travelSubsidiesRequestItemDetailDTOs[detailIndex];
    if (Number(value) > 0) {
      detail.currencyRate = value;
      this.setState({subsidyInfo});
    }
  };

  amountChange = (value, detailIndex) => {
    let { subsidyInfo } = this.state;
    let detail = subsidyInfo.travelSubsidiesRequestItemDetailDTOs[detailIndex];
    if (Number(value) >= 0) {
      detail.amount = value;
      this.setState({subsidyInfo});
    }
  };

  handleUpdate = (e, detailIndex, isRemove) => {
    e.stopPropagation();
    e.preventDefault();
    const { newProfile } = this.props;
    let amountModify = newProfile['subsidyControlOpt']['amountModify'];
    let { subsidyInfo } = this.state;
    let detail = subsidyInfo.travelSubsidiesRequestItemDetailDTOs[detailIndex];
    if (isRemove) {
      detail.deleted = true;
      eventTrack({
        category: '计算补贴',
        action: '删除单个差补明细'
      });
    } else {
      eventTrack({
        category: '计算补贴',
        action: '差补明细行-保存'
      });
      //如果不是操作删除，要进行汇率和金额的校验
      if (this.getRateType() === 'error') {
        message.error(messages('request-1.key422')/*请修改汇率*/);
        return;
      }
      if(amountModify === 1002 && Number(detail.amount) > Number(detail.baseAmount)){
        message.error(messages('request-1.key423')/*金额不可大于原金额*/);
        return;
      }
    }
    this.setState({loading: true});
    travelService.updateSubsidyDetail([detail]).then(res => {
      //刷新金额和差补明细
      this.refreshSubsidyInfo();
      sessionStorage.setItem('isNeedApplicationRefresh', 'true');
    }).catch(err => {
      errorMessage(err.response);
      this.setState({loading: false});
    });
  };

  refreshSubsidyInfo = () => {
    const { subsidyInfo } = this.state;
    const { refreshSubsidy } = this.props;
    const { formRefKey } = this.props.params;
    requestService.getItineraryBudget(subsidyInfo.applicationCustomBudgetId).then(res => {
      this.setState({loading: false, subsidyInfo: JSON.parse(JSON.stringify(res.data))}, () => {
        refreshSubsidy(res.data, formRefKey, subsidyInfo.applicationCustomBudgetId);
      });
    }).catch(err => {
      errorMessage(err.response);
      this.setState({loading: false});
    });
  };

  //获取单个差补修改汇率下的提示文案
  getMessage = () => {
    const { info } = this.props.params;
    const { subsidyInfo } = this.state;
    let subsidyItem = {};
    let isHasEdit = false;
    subsidyInfo.travelSubsidiesRequestItemDetailDTOs && subsidyInfo.travelSubsidiesRequestItemDetailDTOs.forEach(item => {
      if (item.isEdit) {
        isHasEdit = true;
        subsidyItem = JSON.parse(JSON.stringify(item));
      }
    });
    if (!isHasEdit) {
      return;
    }
    subsidyItem.currencyRate = Number(subsidyItem.currencyRate);
    subsidyItem.amount = Number(subsidyItem.amount);

    let currencyCode = info.currencyCode; //本位币
    let rateStr = `${subsidyItem.baseCurrencyRate.toFixed(7)}
    ${(subsidyItem.currencyRate - subsidyItem.baseCurrencyRate) < 0 ? ' - ' : ' + '}
    ${(Math.abs(subsidyItem.currencyRate - subsidyItem.baseCurrencyRate) / subsidyItem.baseCurrencyRate * 100).toFixed(1)}%`;
    let baseAmount = 0;
    if (subsidyItem.amount && subsidyItem.currencyRate) {
      baseAmount = subsidyItem.amount * subsidyItem.currencyRate;
    }
    baseAmount = React.Component.prototype.filterMoney(baseAmount, queryCurrencyPrecision(currencyCode), true);
    return <span>{messages('request-1.key424')/*企业汇率：*/}{rateStr}&nbsp;&nbsp;{messages('request-1.key425')/*本币金额：*/}{baseAmount}</span>;
  };

  //获取容差情况，是在警告，还是禁止，还是都ok的状态
  getRateType = () => {
    const { warnExchangeRateTol, prohibitExchangeRateTol } = this.props.params;
    const { subsidyInfo } = this.state;
    let subsidyItem = {};
    let isHasEdit = false;
    subsidyInfo.travelSubsidiesRequestItemDetailDTOs && subsidyInfo.travelSubsidiesRequestItemDetailDTOs.forEach(item => {
      if (item.isEdit) {
        isHasEdit = true;
        subsidyItem = JSON.parse(JSON.stringify(item));
      }
    });
    if (!isHasEdit) {
      return;
    }
    subsidyItem.currencyRate = Number(subsidyItem.currencyRate);
    subsidyItem.amount = Number(subsidyItem.amount);

    let type = 'info';
    let change = (Math.abs(subsidyItem.currencyRate - subsidyItem.baseCurrencyRate) / subsidyItem.baseCurrencyRate * 100).toFixed(1);
    if (warnExchangeRateTol && change > warnExchangeRateTol) {
      type = 'warning';
    }
    if (prohibitExchangeRateTol && change > prohibitExchangeRateTol) {
      type = 'error';
    }
    return type;
  };

  isHasEdit = () => {
    const { subsidyInfo } = this.state;
    let isHasEdit = false;
    subsidyInfo.travelSubsidiesRequestItemDetailDTOs && subsidyInfo.travelSubsidiesRequestItemDetailDTOs.forEach(item => {
      if (item.isEdit) {
        isHasEdit = true;
      }
    });
    return isHasEdit;
  };

  render() {
    const { loading, subsidyInfo, isOpen } = this.state;
    const { newProfile, disabled } = this.props;
    const { prohibitExchangeRateTol } = this.props.params || {};
    let amountModify = newProfile['subsidyControlOpt']['amountModify'];
    return (
      <div className="itinerary-subsidy-detail">
        <Spin spinning={loading}>
          <Row type="flex" align="middle" style={{marginBottom: 20}}>
            <span className="subsidy-expense-amount">
              {requestUtil.getAmountStr(null, subsidyInfo)}
            </span>
            <span className="icon-btn" onClick={this.toggleDrop}>
              {messages('request-1.key426')/*明细*/}&nbsp;<Icon type={isOpen ? "up" : "down"} />
            </span>
          </Row>
          {isOpen && this.isHasEdit() && (
            <Alert message={this.getMessage()} type={this.getRateType()} showIcon style={{marginBottom: 12}} />
          )}
          <div className={`subsidy-fake-table ${isOpen ? 'opened' : ''}`}>
            {subsidyInfo.travelSubsidiesRequestItemDetailDTOs && subsidyInfo.travelSubsidiesRequestItemDetailDTOs.map((detail, detailIndex) => {
              return (
                <Row type="flex" align="middle" className="detail-row">
                  <Col span={disabled ? 4 : 3}>
                    {moment(detail.subsidiesDate).format('YYYY-MM-DD')}
                  </Col>
                  <Col span={disabled ? 4 : 3}>
                    {detail.userName}
                  </Col>
                  <Col span={4}>
                    {detail.expenseTypeName}
                  </Col>
                  <Col span={6}>
                    <If value={detail.isEdit && (amountModify === 1002 || amountModify === 1003)}>
                      {detail.currencyCode}
                      <InputNumber
                        style={{width: '60%'}}
                        min={0}
                        precision={queryCurrencyPrecision(detail.currencyCode)}
                        value={detail.amount}
                        onChange={(value) => this.amountChange(value, detailIndex)}
                      />
                    </If>
                    <If value={!detail.isEdit || !(amountModify === 1002 || amountModify === 1003)}>
                      {requestUtil.renderAmountStr(detail.currencyCode, detail.amount)}
                    </If>
                  </Col>
                  <Col span={disabled ? 6 : 4}>
                    {/*差补汇率不让修改*/}
                    {Number(detail.currencyRate).toFixed(7)}
                  </Col>
                  <Col span={disabled ? 0 : 2}>
                    <If value={!disabled && this.isShowEdit() && !detail.isEdit}>
                      <Icon type="edit" style={{color: '#6C788C', cursor: 'pointer'}} onClick={() => this.handleEdit(detailIndex)}/>
                    </If>
                    <If value={detail.isEdit}>
                      <span
                        onClick={(e) => this.handleUpdate(e, detailIndex)}
                        style={{color: '#4B8DFF', fontSize: '12px', cursor: 'pointer'}}
                      >
                        {messages('common.save')/*保存*/}
                      </span>
                    </If>
                  </Col>
                  <Col span={disabled ? 0 : 2}>
                    <If value={detail.isEdit}>
                      <span
                        onClick={this.handleCancel}
                        style={{color: '#6C788C', fontSize: '12px', cursor: 'pointer'}}
                      >
                        {messages('common.cancel')/*取消*/}
                      </span>
                    </If>
                    <If value={!detail.isEdit}>
                      <Popconfirm onConfirm={(e) => this.handleUpdate(e, detailIndex, true)} title={messages('request-1.key386')/*你确认要删除？*/}>
                        <Icon style={{cursor: 'pointer'}} type="delete" />
                      </Popconfirm>
                    </If>
                  </Col>
                </Row>
              )
            })}
          </div>
        </Spin>
      </div>
    )
  }
}

RequestSubsidyDetail.propTypes = {
  subsidyInfo: React.PropTypes.object,
  refreshSubsidy: React.PropTypes.func,
  disabled: React.PropTypes.bool,
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    newProfile: state.login.options
  }
}

export default connect(mapStateToProps)(RequestSubsidyDetail);
